<template>
  <d2-container :filename="filename">
    <el-row>
      <el-col :span="8" :lg="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>分组</span>
          </div>
          <div  class="text item">
            <el-form :inline="true" :model="formTree" ref="formTree" size="mini" style="margin-bottom: -18px;">
              <el-form-item label="关键字" prop="key">
                <el-input v-model="formTree.key" placeholder="关键字" style="width: 100px;" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleTreeFormSearch">
                  <d2-icon name="search" /> 查询
                </el-button>
              </el-form-item>
            </el-form>
            <br/>
            <el-tree
              :data="treeData"
              :props="defaultTeeProps"
              :current-node-key="treeSelectedId"
              node-key="id"
              ref="tree"
              default-expand-all
              :expand-on-click-node="false"
              highlight-current
              @check-change="handleTreeCheckChange"
              @node-click="handleNodeClick">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                  <el-button
                    type="text"
                    size="mini"
                    @click="() => handleAddGroup(data)">
                    添加
                  </el-button>
                  <el-button v-if="data.id!=0"
                    type="text"
                    size="mini"
                    @click="() => handleEditGroup(data)">
                    编辑
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="() => handleRemoveGroup(node, data)">
                    删除
                  </el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </el-card>
      </el-col>
      <el-col :span="16" :lg="18">
        <el-form :inline="true" :model="form" :rules="rules" ref="form" size="mini" style="margin-bottom: -18px;">
          <el-form-item label="关键字" prop="key">
            <el-input v-model="form.key" placeholder="关键字" style="width: 100px;" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFormSubmit">
              <d2-icon name="search" /> 查询
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleFormReset">
              <d2-icon name="refresh" /> 重置
            </el-button>

          </el-form-item>
          <el-form-item>
            <el-button @click="handleAddItem">新增</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="table"    stripe style="width: 100%">
          <el-table-column prop="key" label="关键字" >
          </el-table-column>
          <el-table-column prop="name" label="名称" >
          </el-table-column>
          <el-table-column prop="value" label="值" >
          </el-table-column>
          <el-table-column label="创建时间"  :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{scope.row.create_time | moment("YYYY-MM-DD HH:mm:ss")}}
            </template>
          </el-table-column>
          <el-table-column  label="操作" width="120">
          <template slot-scope="scope">
              <el-button
              type="text"
              size="small"   @click.native.prevent="handleEditGroup(scope.row)">
              编辑
            </el-button>
          </template>
          </el-table-column>
        </el-table>
        <sx-pagination
        :current-page="page.current"
        :page-size="page.size"
        :total="page.total"
        @pagination="handlePaginationChange" >
        </sx-pagination>
      </el-col>
    </el-row>
    <el-dialog :title="EditTitleMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="tempData" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">

        <el-form-item label="Key" prop="key">
          <el-input v-model="tempData.key"/>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="tempData.name"/>
        </el-form-item>
        <el-form-item label="值" prop="value">
          <el-input v-model="tempData.value"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="tempData.remark"/>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="tempData.type" class="filter-item" placeholder="请选择">
            <el-option v-for="item in typeOptions" :key="item.label" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="tempData.status" class="filter-item" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item.label" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="父亲节点" prop="parent_id">
           <el-select v-model="tempData.parent_id" class="filter-item" placeholder="请选择">
            <el-option v-for="item in groupDatas" :key="item.name" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
            <el-input-number v-model="tempData.sort"  :min="0" ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="SaveData()">保存</el-button>
      </div>
    </el-dialog>
  </d2-container>
</template>

<script>
import { GetCodeList, GetCodeTreeList, DeleteCode, SaveCode } from '@/api/sys/code'
import util from '@/libs/util.js'
export default {
  // name 值和本页的 $route.name 一致才可以缓存页面
  name: 'sys-log-index',
  components: {
    // 'DemoPageHeader': () => import('./componnets/PageHeader'),
    // 'DemoPageMain': () => import('./componnets/PageMain')
  },
  data () {
    return {
      filename: __filename,
      table: [],
      loading: false,
      groupDatas: [],
      page: {
        current: 1,
        size: 20,
        total: 0
      },
      // 类型选项数据
      typeOptions: [{ label: '分组', value: 1 }, { label: '值', value: 2 }],
      // 状态选项数据
      statusOptions: [{ label: '显示', value: 0 }, { label: '隐藏', value: 1 }],
      formTree: {
        key: ''
      },
      form: {
        key: '',
        parent_id: 0
      },
      rules: {
      },
      defaultTeeProps: {
        children: 'children',
        label: 'name'
      },
      treeData: [],
      treeSelectedId: 0,
      // 编辑按钮
      dialogFormVisible: false,
      // 弹窗模式
      dialogStatus: 'create',
      // 弹窗标题
      EditTitleMap: {
        create: '创建',
        update: '编辑',
        view: '查看'
      },
      // 创建表单临时数据
      tempData: {
        id: 0,
        key: '',
        value: '',
        status: 0,
        remark: '',
        name: '',
        type: 0,
        parent_id: 0,
        sort: 0
      }

    }
  },
  created () {
    this.$nextTick(() => {
      this.handleTreeFormSearch()
      this.handleFormSubmit()
    })
  },
  methods: {
    handlePaginationChange (val) {
      // val.total = this.page.total
      this.page = val

      this.$nextTick(() => {
        this.handleFormSubmit()
      })
      // this.page.size = val
    },
    handleSubmit (form) {
      this.loading = true
      GetCodeList({
        form,
        page: this.page
      })
        .then(res => {
          this.loading = false
          this.table = res.list
          this.page = res.page
        })
        .catch(err => {
          this.loading = false
          this.$notify({
            title: '数据请求异常'
          })
          console.log('err', err)
        })
    },
    handleFormSubmit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.handleSubmit(this.form)
        } else {
          this.$notify.error({
            title: '错误',
            message: '表单校验失败'
          })
          return false
        }
      })
    },
    handleFormReset () {
      this.$refs.form.resetFields()
    },
    handleTreeFormSearch () {
      GetCodeTreeList(this.formTree).then(res => {
        this.loading = false

        let datas = util.formatList2Tree(res.data)
        let data = res.data
        data.unshift({ id: 0, name: '根节点' })
        this.groupDatas = data
        this.treeData = [
          {
            id: 0,
            name: '所有',
            children: datas
          }
        ]
      }).catch(err => {
        this.loading = false
        this.$notify({
          title: '数据请求异常'
        })
        console.log('err', err)
      })
    },
    handleNodeClick (val) {
      this.form.parent_id = val.id
      this.$nextTick(() => {
        this.handleFormSubmit()
      })
    },
    handleTreeCheckChange (data, checked, indeterminate) {
      // console.log(data, checked, indeterminate)
      // console.log(this.treeSelectedId)
    },
    resetTemp (pid) {
      this.tempData = {
        id: 0,
        key: '',
        value: '',
        status: 0,
        remark: '',
        name: '',
        type: 0,
        parent_id: pid,
        sort: 0
      }
    },
    // 添加
    handleAddGroup (data) {
      this.resetTemp(data.id)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAddItem () {
      this.resetTemp(this.form.parent_id)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEditGroup (data) {
      this.tempData = Object.assign({}, data) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 删除分组
    handleRemoveGroup (node, data) {
      var _t = this
      util.RemoveData(DeleteCode, { id: data.id }, _t, function () {
        _t.handleTreeFormSearch()
      })
    },
    // 更新数据
    SaveData () {
      var _t = this
      util.SaveData(SaveCode, _t.tempData, _t, function () {
        _t.handleTreeFormSearch()
      })
    }
  }
}
</script>

<style>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 90%;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
